﻿using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using Macad.Common.Evaluator;
using Macad.Common.Interop;
using Macad.Core;
using Macad.Core.Topology;
using Macad.Interaction;
using SpCad.Servers;
using SpCad.Utils;
using SpCad.Window; 
namespace SpCad
{
    /// <summary>
    /// CadControl.xaml 的交互逻辑
    /// </summary>
    public partial class CadControl : UserControl, ISpView
    {
       
   
        public static CadControl Current { get; private set; }
        public Select Select { get; set; }// = new Select();
        public SpaceNavigator SpaceNavigator { get; } = new SpaceNavigator();
        private SpCadControlViewModel Model = new SpCadControlViewModel();
        System.Windows.Window thisw;
        public Thickness ClippingBorder
        {
            get { return ViewportPanel.ClippingBorder; }
            set { ViewportPanel.ClippingBorder = value; }
        }

       

        public sFile File { get; }

        public CadControl()
        {
            Current = this;
            InitializeComponent();
            DataContext = Model;
            this.PreviewMouseMove += CadControl_PreviewMouseMove;
            File = new sFile();

            this.Loaded += CadControl_Loaded; ;
        }

        private void CadControl_Loaded(object sender, RoutedEventArgs e)
        {
            //加载配置文件中的工作台 
            LodParametric.DatumPlaneParametric lodpd = new LodParametric.DatumPlaneParametric();
            if (!string.IsNullOrEmpty(lodpd.WorkShape))
            {
                string path = lodpd.WorkShape;

            }
        }

        private void CadControl_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            Point mousePosition = e.GetPosition(this);
            var hitTestResult = VisualTreeHelper.HitTest(this, mousePosition);
            //_context.MoveTo(x, y, _context.MainV3dView(), false);
            //_context.Select();
          
           //var selectedShape = _context.SelectedShape();
        }
        #region 带自方法
        public void SetWindowEnabled(bool bIsEnabled)
        {
            ViewportPanel.SetWindowEnabled(bIsEnabled);
        }
        public void SpCad_Loaded(object sender, RoutedEventArgs e)
        {
            thisw =(System.Windows.Window) sender;

          
            _MainWindow_Loaded(sender, e);
            Unloaded += _MainWindow_Unloaded;
            
            thisw.SourceInitialized += _MainWindow_OnSourceInitialized;
            DragOver += _MainWindow_DragOver;
            Drop += _MainWindow_Drop;
            KeyDown += _MainWindow_KeyDown;

        }
        void _MainWindow_Drop(object sender, DragEventArgs e)
        {
            if (e.Handled)
                return;

            _ImportDroppedFile(_ExtractDropFile(e));
        }
        void _ImportDroppedFile(string filePath)
        {
            if (string.IsNullOrEmpty(filePath) || !ExchangeCommands.ImportDroppedFile.CanExecute(filePath))
                return;

            thisw.Activate();

            ExchangeCommands.ImportDroppedFile.Execute(filePath);
        }
        void _MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // Init Space Navigator
            SpaceNavigator.Init(thisw);

            AppCommands.InitApplication.Execute();
            Dispatcher.CurrentDispatcher.BeginInvoke(AppCommands.RunStartupCommands.Execute, DispatcherPriority.Loaded);

            SpServer.Instance.init();
        }
        void _MainWindow_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.OriginalSource is TextBoxBase)
                return;

             e.Handled = Model.GlobalKeyDown(e);
        }
        void _MainWindow_Unloaded(object sender, RoutedEventArgs e)
        {
            // Deinit space navigator
            SpaceNavigator.DeInit();
        }
        IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
                case Win32Api.WM_DROPFILES:
                    {
                        handled = true;
                        const int maxPath = 260;
                        var hDrop = wParam;
                        var count = Win32Api.DragQueryFile(hDrop, 0xFFFFFFFF, null, 0);
                        if (count > 0)
                            count = 1; // Currently, we only import the first

                        for (uint i = 0; i < count; i++)
                        {
                            int size = (int)Win32Api.DragQueryFile(hDrop, i, null, 0);
                            var filename = new StringBuilder(size + 1);
                            Win32Api.DragQueryFile(hDrop, i, filename, maxPath);

                            _ImportDroppedFile(filename.ToString());
                        }

                        Win32Api.DragFinish(hDrop);
                        break;
                    }

                case Win32Api.WM_ENABLE:
                    {
                        bool bIsEnabled = wParam.ToInt32() == 1;
                        SetWindowEnabled(bIsEnabled);
                        break;
                    }
            }

            return IntPtr.Zero;
        }
        void _MainWindow_OnSourceInitialized(object sender, EventArgs e)
        {
            var hwnd = new WindowInteropHelper(thisw).Handle;
            Win32Api.DragAcceptFiles(hwnd, true);

            var hwndSource = PresentationSource.FromVisual(this) as HwndSource;
            Debug.Assert(hwndSource != null, nameof(hwndSource) + " != null");
            hwndSource.AddHook(WndProc);

            if (!Window.AppContext.IsInSandbox)
            {
                WindowPlacement.LoadWindowPlacement(thisw, "MainWindowPlacement");
            }
            else
            {
                thisw.Left = 0;
                thisw.Top = 0;
            }
 
        }
        void _MainWindow_DragOver(object sender, DragEventArgs e)
        {
            if (ExchangeCommands.ImportDroppedFile.CanExecute(_ExtractDropFile(e)))
            {
                e.Effects = DragDropEffects.None;
                e.Handled = true;
            }
        }
        string _ExtractDropFile(DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                // Note that you can have more than one file.
                var files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (files != null)
                {
                    var filePath = files.First();
                    if (ExchangeCommands.ImportDroppedFile.CanExecute(filePath))
                    {
                        return filePath;
                    }
                }
            }
            return null;
        }

        public void ToolAction_Finished(SelectSubshapeAction sender, SelectSubshapeAction.EventArgs args)
        {
            throw new NotImplementedException();
        }
        #endregion



    }
}
